package com.lyq.blog.controller;

import com.lyq.blog.exception.BlogException;
import com.lyq.blog.model.BlogInfo;
import com.lyq.blog.service.BlogService;
import com.lyq.blog.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;
    /**
     * 获取博客列表
     * @return 返回博客列表
     */
    @RequestMapping("/getList")
    public List<BlogInfo> gitList() {
        log.info("获取博客列表");
        return blogService.getList();
    }
    /**
     * 根据id获取博客
     */
    @RequestMapping("/gitBlogById")
    public BlogInfo gitBlogById(Integer blogId, HttpServletRequest request) {
        String UserToken = request.getHeader("user_token");
        log.info("根据id获取博客  blogId:{} UserToken:{}", blogId, UserToken);
        if (blogId == null || blogId <= 0) {
            throw new BlogException("非法请求");
        }
        BlogInfo blogInfo = blogService.getBlogById(blogId);
        Claims claims = JwtUtil.parserToken(UserToken);
        blogInfo.setIsLoginUser(claims.get("id").equals(blogInfo.getUserId()));
        return blogInfo;
    }
    /**
     * 添加博客
     */
    @RequestMapping("/addBlog")
    public boolean addBlog(BlogInfo blogInfo, HttpServletRequest request) {
        String userToken = request.getHeader("user_token");
        log.info("添加博客 BlogInfo:{} UserToken:{}", blogInfo, userToken);
        Integer userId = (Integer) JwtUtil.parserToken(userToken).get("id");
        blogInfo.setUserId(userId);
        return blogService.addBlog(blogInfo);
    }
    /**
     * 修改博客
     */
    @RequestMapping("/updateBlog")
    public boolean updateBlog(BlogInfo blogInfo) {
        log.info("修改博客");
        Date date = new Date(System.currentTimeMillis());
        blogInfo.setUpdateTime(date);
        log.info("修改博客 blogInfo:{}", blogInfo);
        return blogService.updataBlog(blogInfo);
    }
    /**
     * 删除博客
     */
    @RequestMapping("/deleteBlog")
    public boolean deleteBlog(Integer blogId) {
        log.info("删除博客 blogId:{}", blogId);
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setId(blogId);
        blogInfo.setDeleteFlag(0);
        return blogService.updataBlog(blogInfo);
    }
}
